package cn.admin.configcenter.configservice.service;


import cn.admin.configcenter.configservice.service.event.ConfigChangeEvent;
import cn.admin.configcenter.configservice.service.event.EventDispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
@Scope("singleton")
public class CacheRepositoryManager {

    private static final Logger LOG =
            LoggerFactory.getLogger(CacheRepositoryManager.class);

    private static ConcurrentHashMap<String,String> cacheMap;

    public void setCacheMap(ConcurrentHashMap<String,String> cacheMapFromDB) {
        cacheMap = cacheMapFromDB;
    }

    public String getContentMd5(String configKey) {

        this.makeSureConfigKeyExists(configKey);
        String md5 = cacheMap.get(configKey);
        return md5 == null ? "" : md5;

    }

    public void refreshCache(String configKey,String md5) {

        String cacheMd5 = cacheMap.get(configKey);

        if (cacheMd5 == null || !cacheMd5.equals(md5)) {
            EventDispatcher.fireEvent(new ConfigChangeEvent(configKey));
        }

        cacheMap.put(configKey, md5);

    }

    public void removeCache(String configKey) {

        cacheMap.remove(configKey);
        EventDispatcher.fireEvent(new ConfigChangeEvent(configKey));

    }

    private void makeSureConfigKeyExists(String configKey) {
        cacheMap.putIfAbsent(configKey, "");
    }


}
